package com.snjx.micro.oauth.auth.config;

import cn.hutool.core.util.ArrayUtil;
import com.snjx.micro.oauth.auth.component.JwtTokenEnhancer;
import com.snjx.micro.oauth.auth.service.UserServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.ArrayList;
import java.util.List;

/**
 * @version 1.0
 * @author suonanjiexi
 * @Description TODO
 * @Date 2020/7/30 2:10 下午
 */
@AllArgsConstructor
@Configuration
@EnableAuthorizationServer
@Slf4j
public class Oauth2ServerConfig extends AuthorizationServerConfigurerAdapter {

    private final PasswordEncoder passwordEncoder;
    private final UserServiceImpl userService;
    private final AuthenticationManager authenticationManager;
    private final JwtTokenEnhancer jwtTokenEnhancer;

    private  ClientDetailsServiceConfig clientDetailsServiceConfig;

    /*@Value("#{'${server.name}'.split(',')}")
    private List<String> servers;*/
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        log.info("ClientDetailsServiceConfig  : {}",clientDetailsServiceConfig);
        clients.inMemory()
                //客户端设置
                .withClient("client-app")
                //私钥
                .secret(passwordEncoder.encode("123456"))
                //作用域
                .scopes("all","read","write")
                //授权类型 一共四种
                .authorizedGrantTypes(ArrayUtil.toArray(clientDetailsServiceConfig.getGrantType(),String.class))
                //可访问资源id
                .resourceIds("api","user","order")
                //访问令牌有效期 单位: 秒
                .accessTokenValiditySeconds(clientDetailsServiceConfig.getAccessToken())
                //刷新令牌有效期 单位: 秒
                .refreshTokenValiditySeconds(clientDetailsServiceConfig.getRefreshToken())
                //自动授权配置
                .autoApprove(true)
                //重定向地址
                .redirectUris("https://www.baidu.com")
        ;
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> delegates = new ArrayList<>();
        delegates.add(jwtTokenEnhancer);
        delegates.add(accessTokenConverter());
        //配置JWT的内容增强器
        enhancerChain.setTokenEnhancers(delegates);
        endpoints.authenticationManager(authenticationManager)
                //配置加载用户信息的服务
                .userDetailsService(userService)
                //配置令牌策略
                .accessTokenConverter(accessTokenConverter())
                .tokenEnhancer(enhancerChain);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //security.checkTokenAccess("isAuthoricated()");
        security.allowFormAuthenticationForClients();
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setKeyPair(keyPair());
        return jwtAccessTokenConverter;
    }

    @Bean
    public KeyPair keyPair() {
        //从classpath下的证书中获取秘钥对
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "123456".toCharArray());
        return keyStoreKeyFactory.getKeyPair("jwt", "123456".toCharArray());
    }

}
